package com.phale.domain.utils;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Entities;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.phale.domain.EMF;
import com.phale.domain.Item;

public class ItemFactory {
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();
	private ImagesService imagesService = ImagesServiceFactory
			.getImagesService();

	private static ItemFactory INSTANCE;

	public static ItemFactory get() {
		if (INSTANCE == null) {
			INSTANCE = new ItemFactory();
		}
		return INSTANCE;
	}

	

	public Item buildItemFromRequest(HttpServletRequest req) {
		Item item = new Item();
		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
		List<BlobKey> blobKey = blobs.get("file");
		String keyStr = blobKey.get(0).getKeyString();
		String name = req.getParameter("name");
		String des = req.getParameter("description");

		Image oldImage = ImagesServiceFactory.makeImageFromBlob(blobKey.get(0));
		Transform resize = ImagesServiceFactory.makeResize(200, 300);
		Image newImage = imagesService.applyTransform(resize, oldImage);

		// store this in datastore
		byte[] newImageData = newImage.getImageData();

		Blob blob = new Blob(newImageData);

		item.setBlobKey(keyStr);
		item.setName(name);
		item.setDescription(des);
		item.setImageRz(blob);

		EntityManager mag = EMF.get().createEntityManager();
		EntityTransaction tx = mag.getTransaction();
		tx.begin();

		mag.persist(item);

		mag.flush();

		tx.commit();

		mag.close();

		return item;
	}
}
